package com.yookey.study;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import com.alibaba.android.arouter.launcher.ARouter;
import com.base.commonlib.base.CBaseMvpFragment;
import com.base.commonlib.bean.StatEntity;
import com.base.commonlib.bean.TabEntity;
import com.base.commonlib.bean.UpdateScopeStatEntity;
import com.base.commonlib.bean.User;
import com.base.commonlib.event.TabEnent;
import com.base.commonlib.utils.RxBus2;
import com.base.commonlib.utils.ToastUtil;
import com.base.home.bean.Score;
import com.base.home.fag.ConcertFragment;
import com.base.study.fragment.TestPaperFragment;
import com.yookey.study.adapter.BaseFragmentAdapter;
import com.yookey.study.bean.HomeStatEntity;
import com.yookey.study.databinding.FragmentMainBinding;
import com.yookey.study.presenter.MainPresenter;
import com.yookey.study.view.MainView;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.yokeyword.fragmentation.SupportFragment;

/**
 * Created by weikailiang on 2019/9/19.
 */

public class MainFragment extends CBaseMvpFragment<MainPresenter> implements MainView {
    protected FragmentMainBinding mBinding;
    private BaseFragmentAdapter myAdapter;
    private List<SupportFragment> fragments = new ArrayList<>();
    Disposable homeDisposable;
    @Override
    public void init() {
        mBinding = (FragmentMainBinding) mRootBinding;
        mPresenter = new MainPresenter(this,_mActivity);
        mPresenter.start();
    }

    @Override
    public void start() {
        RxBus2.getInstance().post(new StatEntity(1));
        mBinding.tabManager.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (myAdapter!=null&&myAdapter.getmTitles()!=null){
                    myAdapter.setFragments(getChildFragmentManager(), fragments, myAdapter.getmTitles());
                }
                ARouter.getInstance().build("/home/tabmanager").navigation();
            }
        });
        mBinding.llSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/mystudy/search").navigation();
            }
        });
        mBinding.llMsg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/message/massage").navigation();
//                RxBus2.getInstance().post(new StudyEvent(3));
            }
        });
        mBinding.tab.setTabPaddingLeftAndRight(20, 20);
        mBinding.tab.setSelectedTabIndicatorHeight(5);
        //默认选中第5个
        mBinding.tab.setLastSelectedTabPosition(0);
        //移动到第5个
        mBinding.tab.setCurrentItem(0);

        mBinding.tab.setupWithViewPager(mBinding.viewPager);

        mBinding.homeMine.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ARouter.getInstance().build("/mine/mineact").withString("cover",mBinding.score.getText().toString()).navigation();
            }
        });

         homeDisposable = RxBus2.getInstance().doSubscribe(HomeStatEntity.class, new Consumer<HomeStatEntity>() {
            @Override
            public void accept( HomeStatEntity bean) throws Exception {
                if (bean.getState() == 1){
                    mBinding.tab.setLastSelectedTabPosition(0);
                    //移动到第5个
                    mBinding.tab.setCurrentItem(0);
                }
            }
        });

        Disposable disposable = RxBus2.getInstance().doSubscribe(com.base.commonlib.bean.TabEntity.class, new Consumer<com.base.commonlib.bean.TabEntity>() {
            @Override
            public void accept(final com.base.commonlib.bean.TabEntity bean) throws Exception {
                fragments = createListFragments(bean.getSaved());
                if (myAdapter == null){
                    myAdapter = new BaseFragmentAdapter(getChildFragmentManager(),fragments,bean.getSaved());
                    mBinding.viewPager.setAdapter(myAdapter);
                }else {
                    //刷新fragment
                    myAdapter.setFragments(getChildFragmentManager(),fragments,bean.getSaved());
                }
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable);
        Disposable disposable3 = RxBus2.getInstance().doSubscribe(TabEnent.class, new Consumer<TabEnent>() {
            @Override
            public void accept(final TabEnent bean) throws Exception {
                fragments = createListFragments(myAdapter.getmTitles());
                myAdapter.setFragments(getChildFragmentManager(),fragments,myAdapter.getmTitles());
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable3);
        Disposable disposable1 = RxBus2.getInstance().doSubscribe(Score.class, new Consumer<Score>() {
            @Override
            public void accept(Score bean) throws Exception {
                if (bean.getState() == 0X110){
                    mBinding.score.setText(String.valueOf(bean.getmScore()));
                }

            }
        });

        RxBus2.getInstance().addSubscription(this, disposable1);
        Disposable disposable2 = RxBus2.getInstance().doSubscribe(User.class, new Consumer<User>() {
            @Override
            public void accept(User user) throws Exception {
                mPresenter.initTab();
            }
        });
        RxBus2.getInstance().addSubscription(this, disposable2);
    }


    private List<SupportFragment> createListFragments(List<TabEntity.SavedBean> newsChannel) {
        List<SupportFragment> list = new ArrayList<>();
        ConcertFragment concertFragment = null;
        TestPaperFragment testPaperFragment = null;
        for (int i = 0; i < newsChannel.size(); i++) {
            if (newsChannel.get(i).getType()==1){
                testPaperFragment = new TestPaperFragment();
                Bundle bundle = new Bundle();
                bundle.putString("id", newsChannel.get(i).getId());
                bundle.putString("rondom", UUID.randomUUID().toString());
                testPaperFragment.setArguments(bundle);
                list.add(testPaperFragment);
            }else {
                concertFragment = new ConcertFragment();
                Bundle bundle = new Bundle();
                bundle.putString("id", newsChannel.get(i).getId());
                bundle.putString("rondom", UUID.randomUUID().toString());
                concertFragment.setArguments(bundle);
                list.add(concertFragment);
            }
        }
        return list;
    }
    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_main;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (!hidden){
            RxBus2.getInstance().post(new StatEntity(1));
        }
    }


    @Override
    public ImageView returnStartAsrwake() {
        return mBinding.ivAsrwake;
    }

    @Override
    public void returnVoiceResult(String result) {
        if (!TextUtils.isEmpty(result)) {
            ARouter.getInstance().build("/mystudy/search").withString("kewWord",result).navigation();
        }
    }

    @Override
    public void returnTabList(final List<TabEntity.SavedBean> entities) {
        fragments = createListFragments(entities);
        if (myAdapter == null){
            myAdapter = new BaseFragmentAdapter(getChildFragmentManager(),fragments,entities);
            mBinding.viewPager.setAdapter(myAdapter);
        }else {
            //刷新fragment
            myAdapter.setFragments(getChildFragmentManager(),fragments,entities);
        }

    }

    @Override
    public void returnEmptyTypeList() {
        List<TabEntity.SavedBean> entities =new ArrayList<>();
        /**
         * id : 0
         * name : 推荐
         * sort : 0
         * type : 0
         * parentId : 0
         */
        TabEntity.SavedBean savedBean=new TabEntity.SavedBean();
        savedBean.setId("0");
        savedBean.setName("推荐");
        savedBean.setSort(0);
        savedBean.setType(0);
        savedBean.setId("0");
        entities.add(savedBean);
        fragments = createListFragments(entities);
        if (myAdapter == null){
            myAdapter = new BaseFragmentAdapter(getChildFragmentManager(),fragments,entities);
            mBinding.viewPager.setAdapter(myAdapter);
        }else {
            //刷新fragment
            myAdapter.setFragments(getChildFragmentManager(),fragments,entities);
        }
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mPresenter.release();
        if (homeDisposable!=null){
            homeDisposable.dispose();
        }
    }

}
